package com.wd.live.ui.dailog

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView.Adapter
import com.bumptech.glide.Glide
import com.wd.live.R
import com.wd.live.databinding.DialogSelectGiftBinding
import com.wd.live.databinding.ItemGiftListBinding
import com.wd.live.databinding.ItemTypeListBinding
import com.wd.live.tool.BindingViewHolder
import com.wd.live.tool.LocalData
import com.wd.live.tool.newBindingViewHolder
import com.wd.live.tool.viewBinding

/**
 * 选择直播类型
 * @author nick.wu
 */
class GiftListDialog(context: Context, private val data: MutableList<LocalData.GiftInfo>, private val function: (LocalData.GiftInfo) -> Unit) :
    Dialog(context, R.style.dialog_style) {

    private val binding: DialogSelectGiftBinding by viewBinding()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        initDialogWindow(window, Gravity.BOTTOM)
        setCanceledOnTouchOutside(true)
        initView()
    }

    private fun initView() {
        binding.list.apply {
            adapter = MyAdapter(data) {
                function.invoke(it)
                dismiss()
            }
            layoutManager = GridLayoutManager(context, 3)
        }
    }

    private fun initDialogWindow(window: Window?, gravity: Int) {
        if (window != null) {
            window.setGravity(gravity)
            window.decorView.setPadding(0, 0, 0, 0)
            //获得window窗口的属性
            val lp = window.attributes
            //设置窗口宽度为充满全屏
            lp.width = WindowManager.LayoutParams.MATCH_PARENT
            //设置窗口高度为包裹内容
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT
            //将设置好的属性set回去
            window.attributes = lp
        }
    }

    class MyAdapter(val data: MutableList<LocalData.GiftInfo>, private val function: (LocalData.GiftInfo) -> Unit) :
        Adapter<BindingViewHolder<ItemGiftListBinding>>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindingViewHolder<ItemGiftListBinding> {
            return newBindingViewHolder(parent)
        }

        override fun getItemCount(): Int = data.size

        override fun onBindViewHolder(holder: BindingViewHolder<ItemGiftListBinding>, position: Int) {
            data[position].apply {
                Glide.with(holder.binding.gift).load(imageUrl).into(holder.binding.gift)
                holder.binding.gift
                holder.itemView.setOnClickListener {
                    //执行点击回调
                    function.invoke(this)
                }
            }
        }
    }
}